<?php
namespace app\components;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;


/**
 * Qiniu 图片CDN 上传 
 */
class Qiniu extends \yii\base\Widget
{
    public $auth      = "";
    public $uploadMgr = "";
    public $token     = "";

    /**
     * Starts recording a block.
     */
    public function init()
    {
        $accessKey = \yii::$app->params['accessKey'];
        $secretKey = \yii::$app->params['secretKey'];

        $auth = new Auth($accessKey, $secretKey); 
        $this->auth = $auth;

        $uploadMgr = new UploadManager();
        $this->uploadMgr = $uploadMgr;
    }

    /**
     */
    public function uploadQiniu($filePath, $file_name, $bucket=NULL)
    {
        if(empty($bucket)){
            
            $bucket = \yii::$app->params['bucket'];
        }
        // 生成上传 Token
        $token = $this->auth->uploadToken($bucket);

        // 初始化 UploadManager 对象并进行文件的上传。
        list($ret, $err) = $this->uploadMgr->putFile($token, $file_name, $filePath);

        if ($err !== null) {
            return $err;
        } else {
            return $ret;
        }
    }

}
